//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.qst.crop.controller;

import com.github.pagehelper.PageInfo;
import com.qst.crop.common.Result;
import com.qst.crop.dao.OrderDao;
import com.qst.crop.dao.UserDao;
import com.qst.crop.entity.Expert;
import com.qst.crop.entity.Order;
import com.qst.crop.entity.PasswordParam;
import com.qst.crop.entity.User;
import com.qst.crop.security.service.JwtUserDetailsServiceImpl;
import com.qst.crop.security.util.JwtTokenUtil;
import com.qst.crop.service.ExpertService;
import com.qst.crop.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping({"/user"})
@CrossOrigin
@Api(
        tags = {"用户模块接口"}
)
public class UserController {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private JwtUserDetailsServiceImpl jwtUserDetailsService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ExpertService expertService;

    public UserController() {
    }

    @ApiOperation("用户登录之后，修改用户密码")
    @PostMapping({"/loginUpdatePassword"})
    public Result<String> loginUpdatePassword(@Validated @RequestBody PasswordParam passwordParam, BindingResult bindingResult) {
        String s;
        if (!bindingResult.hasErrors()) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            UserDetails principal = (UserDetails)authentication.getPrincipal();
            s = principal.getUsername();
            User user = this.userService.selectByUserName(s);
            String oldDataBasePassword = user.getPassword();
            String oldPassword = passwordParam.getOldPassword();
            if (!this.passwordEncoder.matches(oldPassword, oldDataBasePassword)) {
                return new Result(false, 20001, "原密码输入错误", "原密码输入错误");
            } else {
                user.setUserName(s);
                user.setPassword(passwordParam.getNewPassword());
                this.userService.update(user);
                return new Result(true, 20000, "修改成功");
            }
        } else {
            StringBuffer stringBuffer = new StringBuffer();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            Iterator var5 = allErrors.iterator();

            while(var5.hasNext()) {
                ObjectError objectError = (ObjectError)var5.next();
                stringBuffer.append(objectError.getDefaultMessage()).append("; ");
            }

            s = stringBuffer.toString();
            System.out.println(s);
            return new Result(false, 20001, "密码修改失败", s);
        }
    }

    @ApiOperation("用户登录之后，根据用户名展示个人信息")
    @GetMapping({"/loginSelectByUsername"})
    public Result<User> loginSelectByUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails principal = (UserDetails)authentication.getPrincipal();
        String username = principal.getUsername();
        User user = this.userService.selectByUserName(username);
        return new Result(true, 20000, "查询成功", user);
    }

    @ApiOperation("用户登录之后，根据用户名修改个人基本信息")
    @PostMapping({"/loginUpdateByUsername"})
    public Result<String> loginUpdateByUsername(@Validated @RequestBody User user, BindingResult bindingResult) {
        String errorInfo;
        if (!bindingResult.hasErrors()) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            UserDetails principal = (UserDetails)authentication.getPrincipal();
            errorInfo = principal.getUsername();
            user.setUserName(errorInfo);
            this.userService.loginUpdateByUsername(user);
            UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(errorInfo);
            String token = this.jwtTokenUtil.generateToken(userDetails);
            return new Result(true, 20000, "修改成功", token);
        } else {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            StringBuffer stringBuffer = new StringBuffer();
            Iterator var5 = allErrors.iterator();

            while(var5.hasNext()) {
                ObjectError error = (ObjectError)var5.next();
                System.out.println(error);
                stringBuffer.append(error.getDefaultMessage()).append("; ");
            }

            System.out.println(stringBuffer);
            errorInfo = stringBuffer.toString();
            return new Result(false, 20001, "修改失败", errorInfo);
        }
    }

    @ApiOperation("查询所有用户")
    @GetMapping
    public Result<List<User>> selectAll() {
        List<User> users = this.userService.selectAll();
        return new Result(true, 20000, "查询成功", users);
    }

    @ApiOperation("增加用户")
    @PostMapping({"/add"})
    public Result<String> add(@RequestBody @Valid User user, BindingResult bindingResult) throws IOException {
        if (!bindingResult.hasErrors()) {
            String userName = user.getUserName();
            User user1 = this.userDao.selectByPrimaryKey(userName);
            if (user1 != null) {
                return new Result(false, 20001, "注册失败", "用户名已被注册，请重新输入");
            } else {
                this.userService.add(user);
                return new Result(true, 20000, "注册成功");
            }
        } else {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            StringBuffer stringBuffer = new StringBuffer();
            Iterator var5 = allErrors.iterator();

            while(var5.hasNext()) {
                ObjectError error = (ObjectError)var5.next();
                System.out.println(error);
                stringBuffer.append(error.getDefaultMessage()).append("; ");
            }

            System.out.println(stringBuffer);
            String errorInfo = stringBuffer.toString();
            return new Result(false, 20001, "注册失败", errorInfo);
        }
    }

    @ApiOperation("根据用户名修改用户信息")
    @PutMapping({"/{userName}"})
    public Result<String> update(@Validated @RequestBody User user, BindingResult bindingResult, @PathVariable("userName") String userName) {
        if (!bindingResult.hasErrors()) {
            user.setUserName(userName);
            this.userService.update(user);
            return new Result(true, 20000, "信息修改成功", "修改成功");
        } else {
            StringBuffer stringBuffer = new StringBuffer();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            Iterator var6 = allErrors.iterator();

            while(var6.hasNext()) {
                ObjectError objectError = (ObjectError)var6.next();
                stringBuffer.append(objectError.getDefaultMessage()).append("; ");
            }

            String s = stringBuffer.toString();
            System.out.println(s);
            return new Result(false, 20001, "信息修改失败", s);
        }
    }

    @ApiOperation("根据用户名删除用户")
    @DeleteMapping({"/{userName}"})
    public Result<String> deletes(@PathVariable("userName") String userName) {
        Order order = new Order();
        order.setOwnName(userName);
        List<Order> orders = this.orderDao.selectByExample(order);
        if (!orders.isEmpty()) {
            return new Result(false, 20001, "删除失败", "该用户有发布的订单，暂不能删除");
        } else {
            this.userService.delete(userName);
            this.expertService.delete(userName);
            return new Result(true, 20000, "删除成功");
        }
    }

    @ApiOperation("根据用户名查询用户")
    @GetMapping({"/{userName}"})
    public Result selectByUserName(@PathVariable("userName") String userName) {
        User user = this.userService.selectByUserName(userName);
        return new Result(true, 20000, "查询成功", user);
    }

    @ApiOperation("分页查询所有用户")
    @GetMapping({"/search/{pageNum}"})
    public Result<PageInfo> findPage(@PathVariable("pageNum") Integer pageNum) {
        PageInfo<User> pageInfo = this.userService.findPage(pageNum);
        return new Result(true, 20000, "分页查询成功", pageInfo);
    }

    @ApiOperation("分页条件查询用户")
    @PostMapping({"/search/{pageNum}/{pageSize}"})
    public Result<PageInfo> findPage(@RequestBody User user, @PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        PageInfo<User> pageInfo = this.userService.findPage(user, pageNum, pageSize);
        return new Result(true, 20000, "查询成功", pageInfo);
    }

    @ApiOperation("查询专家详情")
    @GetMapping({"/searchexpert"})
    public Result searchExpert() {
        UserDetails principal = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = principal.getUsername();
        Expert expert = this.expertService.selectById(name);
        return new Result(true, 20000, "查询成功", expert);
    }

    @ApiOperation("查询所有专家详情")
    @GetMapping({"/searchallexpert"})
    public Result searchAllExpert() {
        List<Expert> experts = this.expertService.selectAllExpert();
        return new Result(true, 20000, "查询成功", experts);
    }

    @ApiOperation("删除专家详情")
    @DeleteMapping({"/deleteexpert/{userName}"})
    public Result deleteExpert(@PathVariable("userName") String userName) {
        this.expertService.delete(userName);
        return new Result(true, 20000, "删除成功");
    }

    @ApiOperation("更新专家详情")
    @PutMapping({"/updateexpert"})
    public Result updateExpert(@RequestBody Expert expert) {
        this.expertService.updateById(expert);
        return new Result(true, 20000, "更新成功");
    }

    @ApiOperation("增加专家详情")
    @PostMapping({"/addexpert"})
    public Result addExpert(@RequestBody Expert expert) {
        this.expertService.insert(expert);
        return new Result(true, 20000, "增加成功");
    }

    @ApiOperation("增加或修改专家详情")
    @PostMapping({"/addUpdexpert"})
    public Result addUpdexpert(@RequestBody Expert expert) {
        UserDetails principal = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = principal.getUsername();
        Expert expertExist = this.expertService.selectById(name);
        expert.setUserName(name);
        if (null != expertExist) {
            this.expertService.updateById(expert);
        } else {
            this.expertService.insert(expert);
        }

        return new Result(true, 20000, "操作成功");
    }
}
